package cn.jiakeyun.umeng_vertify_example

import android.app.Activity
import android.app.Application
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import cn.jiakeyun.umeng_vertify.JKUMAbstractPnsViewDelegate
import cn.jiakeyun.umeng_vertify.UVerifyManager
import cn.jiakeyun.umeng_vertify.UVerifyManagerConfig
import io.flutter.FlutterInjector.instance


class ViewDelegate : JKUMAbstractPnsViewDelegate() {
    var v: View? = null
    val videoView by lazy {
        v?.findViewById<FixedTextureVideoView>(R.id.video_view)
    }
    val wechatLogin by lazy {
        v?.findViewById<ImageView>(R.id.wechat_log)
    }
    val phoneLogin by lazy {
        v?.findViewById<ImageView>(R.id.wechat_phone)
    }
    val closeImg by lazy {
        v?.findViewById<ImageView>(R.id.page_close)
    }
    var dialog: Dialog? = null


    override fun onViewCreated(p0: View?) {
        v = p0;
        v?.run {
            val p = layoutParams
            val dm = context.resources.displayMetrics
            p.width = dm.widthPixels
            p.height = dm.heightPixels + getStatusBarHeight(context)
            layoutParams = p
        }
        initVideo()
        wechatLogin?.setOnClickListener {
            showLoading()
            UVerifyManagerConfig.nativeViewClick2FlutterListener?.click("wechatLogin")
        }
        phoneLogin?.setOnClickListener {
            UVerifyManagerConfig.uMVerityManager?.dismissVerify()
        }
        closeImg?.setOnClickListener {
            UVerifyManagerConfig.uMVerityManager?.dismissVerify()
        }
        UVerifyManagerConfig.initLoginListener(object : UVerifyManager.LoginListener {
            override fun login() {
                showLoading()
            }

            override fun loginField() {
                DialogInstance.instance.hideDialog()
            }
        })
    }


    private fun initVideo() {
        videoView?.run {
            val uri =
                "android.resource://" + v?.context?.packageName.toString() + "/" + R.raw.live_video
            setVideoURI(Uri.parse(uri))
            setOnPreparedListener(MediaPlayer.OnPreparedListener {
                keepScreenOn = true
                it.setVolume(0f, 0f)
                it.isLooping = true
                it.start()
            })
        }
    }

    //获取状态栏高度
    private fun getStatusBarHeight(context: Context): Int {
        var result = 0
        val resourceId: Int = context.resources.getIdentifier(
            "status_bar_height", "dimen", "android"
        )
        if (resourceId > 0) {
            result = context.resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    fun showLoading() {
        DialogInstance.instance.showDialog(ActivityManager.activity!!)
    }

}